package logic

import (
	"automated-modeling/automatedrpc/automatedrpc"
	"automated-modeling/automatedrpc/internal/svc"
	"automated-modeling/models/cache"
	"automated-modeling/models/mysql"
	"automated-modeling/pkg"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(in *automatedrpc.UpdatePasswordRequest) (*automatedrpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line

	get := cache.Rdb.Get(l.ctx, "sendSms"+"updatePassword"+in.Mobile)
	if get.Val() != in.SmsCode {
		return nil, fmt.Errorf("验证码输入错误,请重新输入")
	}

	if in.NewPassword == in.OldPassword {
		return nil, fmt.Errorf("新密码不能和原密码相同")
	}

	var user mysql.Users

	user = mysql.Users{
		Password: pkg.Md5(in.NewPassword),
	}

	err := mysql.DB.Debug().Where("mobile = ?", in.Mobile).Updates(&user).Error
	if err != nil {
		return nil, fmt.Errorf("修改失败")
	}

	cache.Rdb.Del(l.ctx, "sendSms"+"updatePassword"+in.Mobile)

	return &automatedrpc.UpdatePasswordResponse{}, nil
}
